import qs from 'qs';
import axios from 'axios';
const App = {
    data: function () {
        return {
            order: 0,
            questionData: {},
            myAnswer: -1,
            myResults: []
        }
    },
    template: `
    <div>
        <div v-if="myResults.length > 0">
            {{myResults.length}}
           <div v-for="item in myResults">
                <div>题号：{{ item.id }}</div>
                <div>问题：{{ item.question }}</div>
                <div>你的答案：{{ item.myAnswer }}</div>
                <div>正确答案：{{ item.rightAnswer }}</div>
                <div>是否正确：{{ isRight(item.isRight) }}</div>
           </div>
        </div>
        <div v-else>
            <h1>编号{{questionData.id}}</h1>
            <p>{{questionData.question}}</p>
            <div>
                <button 
                v-for="(item,index) in questionData.items" 
                :key="item"
                @click="selectAnswer(index)">
                {{item}}
                </button>
            </div>
        </div>
    </div>
    `,
    mounted() {
        this.getQuestion(this.order)
    },
    computed: {
        isRight() {
            return function (isRight) {
                return isRight ? '正确' : '错误'
            }
        }
    },
    methods: {
        getQuestion(order) {
            axios.post(
                'http://localhost:8000/getQuestions', qs.stringify({ order }))
                .then((res) => {
                    if (res.data.errorCode) {
                        this.myResults = res.data.data;
                        console.log(this.myResults)
                        return;
                    }
                    this.questionData = res.data.data;
                })
        },
        selectAnswer(index) {
            this.myAnswer = index;
            this.order += 1;
        },
        updateAnswer(order, myAnswer) {
            axios.post(
                'http://localhost:8000/updateAnswer',
                qs.stringify({ order, myAnswer })
            );
        }
    },
    watch: {
        order(newValue, oldValue) {
            this.updateAnswer(oldValue, this.myAnswer);
            this.getQuestion(newValue);
        }
    }
}
var vm = Vue.createApp(App).mount('#app');
